package io.renren.modules.backstage.entity;

import io.renren.modules.backstage.controller.CameraVideoController;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CameraThread {

    public static class MyRunnable implements Runnable {
        private static int core = Runtime.getRuntime().availableProcessors();

        // 创建线程池
        public  static ExecutorService threadPool = new ThreadPoolExecutor(
                core, core*4, 3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(core), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        private CameraBean cameraBean;
        public MyRunnable(CameraBean cameraBean) {
            this.cameraBean = cameraBean;
        }

        // 中断线程
        public void setInterrupted(String key) {
            RtmpPush.RTMPPUSHMAP.get(key).setExitCode(1);
        }

        @Override
        public void run() {
            // 直播流
            try {
                CameraVideoController.STREAMMAP.put(cameraBean.getToken(), cameraBean);

                // 执行转流推流任务
                RtmpPush push = new RtmpPush(cameraBean);
                RtmpPush.RTMPPUSHMAP.put(cameraBean.getToken(), push);
                push.push();

                // 清除缓存
                CameraVideoController.STREAMMAP.remove(cameraBean.getToken());
                CameraVideoController.JOBMAP.remove(cameraBean.getToken());
                RtmpPush.RTMPPUSHMAP.remove(cameraBean.getToken());
            } catch (Exception e) {
                e.printStackTrace();
                CameraVideoController.STREAMMAP.remove(cameraBean.getToken());
                CameraVideoController.JOBMAP.remove(cameraBean.getToken());
                RtmpPush.RTMPPUSHMAP.remove(cameraBean.getToken());
            }
        }
    }
}

